import React from 'react'
import { history } from 'umi'
import { BasicLayoutProps, Settings as LayoutSettings } from '@ant-design/pro-layout'
import defaultConfig from '../config/defaultConfig'
import HeaderBreadcrumb from '@/components/HeaderBreadcrumb'
import RightContent from '@/components/RightContent'
import { HttpGetToken } from '@/services'
import { config } from '@amap/amap-react'
import { setStore, StoreKey } from '@/utils/util'

config.key = '425e0738bcf23bba44d1e7382e8be20c'
config.plugins = ['AMap.ToolBar', 'AMap.MoveAnimation', 'AMap.GeoLocation'] as any

interface InitialState {
    user?: IT.IUser
    settings?: LayoutSettings
    collapsed?: boolean
}
if (process.env.NODE_ENV === 'development') {
    window.$bty?.jsGlobal?.send(window.$bty.IpcEvent.APP_DEVTOOLS_TOGLE)
}
export const getInitialState = async (): Promise<InitialState> => {
    try {
        const res = await HttpGetToken()
        if (res.flag === 1) {
            await setStore(StoreKey.USER_INFO, res.data.user)
            await setStore(StoreKey.TOKEN, res.data.token)
            return {
                user: res.data.user,
                settings: defaultConfig,
                collapsed: true, // 是否合起菜单
            }
        }
        throw new Error(res.message)
    } catch (error) {
        console.log(error)
        return { settings: defaultConfig, collapsed: false }
    }
}

export const layout = ({ initialState }: { initialState: InitialState }) => {
    return {
        disableContentMargin: false,
        menuHeaderRender: undefined,
        collapsedButtonRender: false,
        collapsed: initialState.collapsed,
        rightContentRender: () => <RightContent />,
        onPageChange: () => {},
        headerContentRender: (props: BasicLayoutProps & { breadcrumb: any }) => {
            if (props.breadcrumb[history.location.pathname]) {
                return <HeaderBreadcrumb props={props} />
            }
        },
        ...initialState?.settings,
    }
}
